/**
 * Admin/ResourceController
 *
 * 文件上传API 
 */
var AllowTypes = [
    "text/plain",
    "image/gif",
    "image/jpeg",
    "image/png",
    "video/mpeg",
    "application/pdf",
    "application/msword"
];
var path = require("path");
var fs = require("fs");
const crypto = require("crypto");
const sharp = require("sharp");
const os = require("os");

module.exports = {

    // 文件上传插件
    index: function(req, res, next) {
        if (req.method !== "POST") {
            return next();
        }
        console.log("开始上传");
        res.setHeader("Content-Type", "text/html; charset=utf-8");
        req.file('imgFile').upload({
            // don't allow the total upload size to exceed ~10MB
            maxBytes: 10000000
        }, function whenDone(err, uploadedFiles) {
            try {
                if (err) {
                    throw "upload error";
                }

                if (uploadedFiles.length === 0) {
                    throw "No file was uploaded";
                }

                // 目前支持单个文件上传
                var currentFile = uploadedFiles[0];
                var type = currentFile.type;
                if (AllowTypes.indexOf(type) == -1) {
                    throw "error file type";
                }

                var now = new Date();
                var dateStr = now.toLocaleDateString().replace(/\//g, "_");
                var uploadBaseDir = __dirname + "/../../../assets/uploads";
                var uploadDir = uploadBaseDir + path.sep + dateStr;
                var extName = path.extname(currentFile.filename);


                if (!fs.existsSync(uploadBaseDir)) {
                    if (fs.mkdirSync(uploadBaseDir, 775)) {
                        throw "mkdir fail";
                    }
                }
                if (!fs.existsSync(uploadDir)) {
                    if (fs.mkdirSync(uploadDir, 775)) {
                        throw "mkdir fail";
                    }
                }

                sharp(currentFile.fd)
                    .resize(800)
                    .max()
                    .toFormat('jpeg')
                    .toBuffer()
                    .then((outputBuffer) => {
                        var hashBuilder = crypto.createHash('md5');
                        hashBuilder.update(outputBuffer);
                        var resFileName = hashBuilder.digest('hex') + extName;

                        var url = "/uploads/" + dateStr + "/" + resFileName;
                        var targeFileName = uploadDir + path.sep + resFileName;

                        fs.writeFile(targeFileName, outputBuffer, (err) => {
                            if (err) {
                                return next(err);
                            }
                            return res.json({
                                "error": 0,
                                "url": url
                            });
                        });
                    });

            } catch (err) {
                return res.json({
                    "error": 1,
                    "url": null,
                    "message": err
                });
            }
        });
    }
};